<?php

namespace App\Ad\MediaApi\Gdt;

use App\Ad\MediaApi\MediaApiBase;
use YQ\YqExtend;

class GdtApiBase extends MediaApiBase
{
    protected $_host = 'https://api.e.qq.com/v1.3/';

    public function __construct()
    {
        parent::__construct();
    }

    // 随机字符串
    public function getNonce()
    {
        $rand = YqExtend::uniqid32();
        return substr($rand, 8, 16);
    }

    public function send($uri, $access_token, $data, $nonce = null, $is_post = true, $is_all = false)
    {
        $headers = [
            'Content-Type: application/json',
        ];

        $now   = time();
        $nonce = $nonce ?? $this->getNonce();
        $url   = $this->_host . $uri . "?access_token={$access_token}&timestamp={$now}&nonce={$nonce}";
        if ($is_post) {
            $data = json_encode($data, JSON_UNESCAPED_UNICODE);
        }

        $res = $this->curl($url, $data, $is_post, true, 30, false, $headers);
        if ($res[0] != 200) {
            yqlog($url, $data, $res);
            return -1;
        }

        $res = json_decode($res[1], true);
        if ($res['code'] != 0) {
            yqlog($url, $data, $res);
            return $res['message_cn'] ?? $res['message'];
        }

        return $is_all === false ? $res['data'] : $res;
    }
}
